#!/bin/dash

#----
# Modified dmenu_run from suckless, that uses an history file to store
# the most recent commands introduced and display them the first ones
# on the list.
#
# Requires dmenu, ed and stest (part of dmenu)
#----

# Hard dependencies:
deps="ed head dmenu"
for dep in $deps; do
	type $dep >/dev/null || exit 1
done
unset dep deps

hist=/tmp/dmenu_run_hist_history
cache=/tmp/dmenu_run

perm_hist="${XDG_CONFIG_HOME:-"$HOME/.config"}/${hist##*/}"
# the same cache as used by vanilla dmenu_run
perm_cache="${XDG_CACHE_HOME:-"$HOME/.cache"}/${cache##*/}"

# load cache and history into RAM
[ -r "$cache" ] || cp -f "$perm_cache" "$cache"
[ -r "$hist" ] || cp -f "$perm_hist" "$hist"

histmax=50 # maxinum number of commands kept in history

#~ oldifs="$IFS"
#~ IFS="$oldifs"

cmd=$(cat "$hist" "$cache" | dmenu -i "$@")
dash -c "$cmd" &

{ # Update history in background
    [ -z "$cmd" ] || ! hash ${cmd%% *} && exit
    ed -s "$hist"  <<EOF || echo $cmd > "$hist"
g/^${cmd}\$/d
1i
$cmd
.
wq
EOF
# copy back out of RAM to hard drive
head -$histmax "$hist" > "$perm_hist"
diff "$perm_hist" "$hist" >/dev/null || cp -f "$perm_hist" "$hist"
} &

# updating the cache has been moved to a pacman hook
